<template>
  <div class="app-container">
    <div class="filter-container">
      <el-row>
        <el-col :span="12">          
            筛选
            <el-radio-group v-model="filterForm.fileType">
              <el-radio :label="item.value" v-for="(item,key) in documentTypeOptions" :key="key">{{item.label}}</el-radio>
            </el-radio-group>
        </el-col>
        <el-col :span="12" style="text-algin:right">
          <el-button class="filter-item" style="margin-left: 10px;" type="default"  @click="handleCreate">
              目录管理
            </el-button>
        </el-col>
        <el-col :span="12">    
            <el-input v-model="filterForm.title" placeholder="请输入文件标题\文件ID" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
            <el-select v-model="filterForm.catalogueID" filterable remote :remote-method="loadCatalogueList" placeholder="请选择">
              <el-option v-for="item in catalogueFilterOptions" :key="item" :label="item.title" :value="item.identity" />
            </el-select>
        </el-col>
        <el-col :span="12" style="text-algin:right">
            <el-button class="filter-item" style="margin-left: 10px;" type="primary" @click="handleCreate">
              文件上传
            </el-button>
        </el-col>
      </el-row>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.ID }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标题" min-width="150px">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleUpdate(row)">{{ row.originalName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="大小" class-name="status-col" width="100">
        <template slot-scope="{row}">
          {{ row.dimension }}
        </template>
      </el-table-column>
      <el-table-column label="文件类型" class-name="status-col" width="100">
        <template slot-scope="{row}">
          {{ row.documentType }}
        </template>
      </el-table-column>
      <el-table-column label="修改时间" class-name="status-col" width="100">
        <template slot-scope="{row}">
          {{ row.updatedAt }}
        </template>
      </el-table-column>
      <el-table-column label="Actions" align="center" width="320" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            修改
          </el-button>
          <el-button v-if="row.status.value === 5" size="mini" type="success" @click="handleModifyStatus(row,6)">
            启用
          </el-button>
          <el-button v-if="row.status.value === 6" size="mini" @click="handleModifyStatus(row,5)">
            禁用
          </el-button>
          <el-button v-if="row.status.value === 1 || row.status.value == 5" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="filterForm.page" :limit.sync="filterForm.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="目录" prop="catalogue_identity">
          <el-select v-model="temp.type" class="filter-item" placeholder="Please select">
            <el-option v-for="item in catalogueOptions" :key="item.identity" :label="item.title" :value="item.identity" />
          </el-select>
        </el-form-item>
        <el-form-item label="文件" prop="attach">
          <el-upload
            class="avatar-uploader"
            action="/api/attachment/document/upload"
            :show-file-list="false"
            :headers="headers"
            name="loadFile"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="temp.full_uri" :src="temp.full_uri" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="标题" prop="original_name">
          <el-input v-model="temp.original_name" />
        </el-form-item>
        <el-form-item label="Remark">
          <el-input v-model="temp.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="Please input" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          Cancel
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          Confirm
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, removeDocumentByID, saveDocument, changeDocumentStatusByID } from '@/api/attachment/document'
import { fetchCatalogueAvailable } from '@/api/attachment/catalogue'
import { getToken } from '@/utils/auth' // get token from cookie
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      documentTypeOptions:[
        {label:"文档",value:1},
        {label:"图片",value:2},
        {label:"视频",value:3},
        {label:"PDF",value:4},
        {label:"PPT",value:5},
        {label:"EXCEL",value:6},
      ],
      filterForm: {
        page: 1,
        perpage: 10,
        keyword: undefined,
        sort: '+id'
      },
      headers: {
        'Accept': 'application/json',
        'Authorization': getToken()
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      catalogueOptions: [],
      catalogueFilterOptions: [],
      sortOptions: [
        { label: '按大小', key: '+dimension' },
        { label: '按大小', key: '-dimension' },
        { label: '按上传时间', key: '+createdDate' },
        { label: '按上传时间', key: '-createdDate' }
      ],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        identity: undefined,
        documentID: undefined,
        original_name: '',
        mime_type: '',
        ext: '',
        dimension: 0,
        attach: '',
        thumb: '',
        remark: '',
        catalogue_identity: undefined,
        status: 6
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '文件编辑',
        create: '文件上传'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
    this.loadCatalogueList()
    this.getCatalogueFilterList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.filterForm).then(response => {
        this.list = response.data.list
        this.total = response.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleAvatarSuccess(res, file) {
      console.log(file)
      const response = file.response
      if (response.status === 200) {
        this.temp.full_uri = response.data.full_uri
        this.temp.attach = response.data.attach
        this.temp.original_name = file.name
      } else {
        this.$message.error(response.msg)
      }
      console.log(file.response.data.attach)
      // this.temp.attach = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      console.log(file)
      const allowedFileType = ['image/gif', 'image/jpg', 'image/jpeg', 'image/png']
      const isJPG = allowedFileType.indexOf(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2
      this.temp.dimension = file.size
      this.temp.ext = file.type.split('/')[1]
      this.temp.mime_type = file.type
      console.log(isJPG)
      if (isJPG < 0) {
        this.$message.error('上传头像图片只能是 JPG PNG GIF 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG >= 0 && isLt2M
    },
    loadCatalogueList(catalogueName) {
      const formData = {
        'catalogueID': this.temp.catalogueID
      }
      if(catalogueName != undefined){
        formData['keyword'] = catalogueName
      }
      fetchCatalogueAvailable(formData).then(res => {
        if(res.status == 200 && res.data.total > 0){
          this.catalogueOptions = res.data.list
        }
      })
    },
    getCatalogueFilterList() {
      const formdata = {
        'catalogueID': this.filterForm.catalogueID
      }
      fetchCatalogueAvailable(formdata).then(response => {
        this.catalogueFilterOptions = response.data.list
      })
    },
    handleFilter() {
      this.filterForm.start = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      changeDocumentStatusByID({ 'documentID': row.identity, 'status': status }).then(response => {
        console.log(response)
        if (response.status === 200) {
          this.$notify({
            title: 'Success',
            message: 'Delete Successfully',
            type: 'success',
            duration: 2000
          })
          this.filterForm.start = 1
          this.getList()
        } else {
          this.$notify({
            title: '操作失败',
            message: response.msg,
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.filterForm.sort = '+id'
      } else {
        this.filterForm.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        identity: undefined,
        documentID: undefined,
        original_name: '',
        mime_type: '',
        ext: '',
        thumb: '',
        dimension: 0,
        attach: '',
        remark: '',
        catalogue_identity: undefined,
        status: 6
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          saveDocument(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
            this.filterForm.start = 1
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          saveDocument(tempData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
            this.filterForm.start = 1
            this.getList()
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('您确定删除吗？').then(_ => {
        removeDocumentByID({ 'documentID': row.identity }).then(response => {
          console.log(response)
          if (response.status === 200) {
            this.$notify({
              title: 'Success',
              message: 'Delete Successfully',
              type: 'success',
              duration: 2000
            })
            this.filterForm.start = 1
            this.getList()
          } else {
            this.$notify({
              title: '操作失败',
              message: response.msg,
              type: 'error',
              duration: 2000
            })
          }
        })
      }).catch(_ => {

      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.filterForm.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
